package com.kehao.leetcode.basic.string;

import org.junit.Test;

public class StringSolution6 {

    public int myAtoi(String s) {
        int startPosition = getVaildStartPosition(s);
        int answer = 0;int endPostion;boolean isNegative = false;
        if(startPosition <0) return answer;
        if(s.charAt(startPosition)=='-'){
            startPosition++;
            isNegative = true;
        }else if(s.charAt(startPosition)=='+'){
            startPosition++;
        }
        endPostion = getVaildEndPostion(s, startPosition);
        String substring = s.substring(startPosition, endPostion + 1);
        int newAnswer;char c;
        for (int i = 0; i < substring.length(); i++) {
            c = substring.charAt(i);
            newAnswer = answer*10+c-'0';
            if(newAnswer/10==answer){
                answer = newAnswer;
            }else {
                return  isNegative? -2147483648: 2147483647;
            }
        }
        answer = isNegative?-answer:answer;
        return answer;
    }

    public int getVaildStartPosition(String s){
        char c;
        for (int i = 0; i < s.length(); i++) {
            c =  s.charAt(i);
            if(c==' ') continue;
            if (c=='-'||c=='+'||(c>='0'&&c<='9'))
                return i;
            return -1;
        }
        return -1;
    }

    public int getVaildEndPostion(String s,int start){
        char c;
        for (int i = start; i < s.length(); i++) {
            c =  s.charAt(i);
            if (!(c>='0'&&c<='9')) return i-1;
        }
        return s.length()-1;
    }

    @Test
    public void myTest01(){
        String s = "2147483648";
        System.out.println(myAtoi(s));
    }

}
